/*
** malloc.h for malloc in /home/alxevo/Documents/projets/malloc
** 
** Made by Thibault Ravera
** Login   <ravera_t@epitech.net>
** 
** Started on  Fri Feb  3 17:00:47 2012 Thibault Ravera
** Last update Sun Feb  5 23:12:03 2012 Thibault Ravera
*/

#ifndef		__MALLOC_H__
#define		__MALLOC_H__

#include	<pthread.h>
#include	<unistd.h>
#include	<stdlib.h>
#include	<stdio.h>
#include	<string.h>

typedef struct		s_header
{
  size_t		prev_size;
  size_t		size;
  void			*prev;
  void			*next;
}			t_header;

typedef struct		s_header_size
{
  size_t		prev_size;
  size_t		size;
}			t_header_size;

typedef struct		s_data_range
{
  void			*head;
  void			*queue;
  void			*next;
}			t_data_range;

#define	_MYSIZE_T		sizeof(size_t)
#define	_MYHEADER_SIZE		(_MYSIZE_T + _MYSIZE_T)
#define	_MYHEADER_INFO_SIZE	sizeof(struct s_data_range)

#define	_MIN_CHUNK		(_MYHEADER_SIZE + _MYHEADER_SIZE)

#define	SIZE_ARRAY_BINS		17
#define	_MYLIST			(SIZE_ARRAY_BINS - 1)
#define	_MAXSIZE_BINS		((_MYLIST * _MYSIZE_T) + _MYSIZE_T)

#define	PINUSE			1

#define	DATA_RANGE(x)		((t_data_range*)((char*)(x)))
#define	NBLOCKS(x)		((x + _MYSIZE_T - 1) / _MYSIZE_T)
#define	MEMORY_REQUEST(x)	((x * _MYSIZE_T) + _MYSIZE_T)

#define	MEM2CHUNK(x)		((t_header*)((char*)(x) - _MYHEADER_SIZE))
#define	CHUNK2MEM(x)		((void*)((char*)(x) + _MYHEADER_SIZE))
#define	NCHUNKSIZE(x)		((t_header_size*)((char*)(x) - _MYHEADER_SIZE))

#define	MIN(x, y)		((x < y) ? x : y)
#define	IS_TOO_SMALL(x, y)	((x - y) ? ((x - y) < _MIN_CHUNK) ? 1 : 0 : 0)

#define	IDX(x)			(((x - _MYSIZE_T) / _MYSIZE_T) - 1)

extern void			*head_heap_ori;
extern void			*head_heap_cur;
extern void			*bins[SIZE_ARRAY_BINS];
extern pthread_mutex_t		lock_list;

void				*malloc(size_t size);
void				*realloc(void *ptr, size_t size);
void				free(void *ptr);

void				*request_more_memory(size_t size);
void				mymalloc_init();
void				exchange_pointer_chunk(void *ptr);
void				split_chunk(void *ptr, size_t size);
void				*search_in_bins(int idx);

int				check_in_data_range(void *ptr);
void				concat_free_blocks(void *ptr);
void				add_to_list(void *ptr);
void				add_to_bins(void *ptr, int idx);

void				*use_free_list(size_t real_size);

void				*create_new_chunk(void *ptr, size_t size);

void				show_alloc_mem();

#endif
